package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.domain.mongo.*;
import com.itheima.service.mongo.MovementService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@Service // dubbo的
public class MovementServiceImpl implements MovementService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisIDService redisIDService;

    @Override
    public void saveMovement(Movement movement) {
        // 0.获取动态pid并设置
        Long pid = redisIDService.getNextID(ConstantUtil.MOVEMENT_ID);
        movement.setPid(pid);
        // 1.保存动态详情
        mongoTemplate.save(movement);
        // 1-1 获取动态(_id）
        ObjectId movementId = movement.getId();

        // 2.添加个人动态表
        MyMovement myMovement = new MyMovement();
        myMovement.setPublishId(movementId); // 动态id
        myMovement.setCreated(movement.getCreated()); // 发布时间
        // 2-1 保存
        mongoTemplate.save(myMovement, ConstantUtil.MOVEMENT_MINE + movement.getUserId()); // 指定发布人用户id

        // 3.查询发布人的好友列表
        Query query = new Query(Criteria.where("userId").is(movement.getUserId()));
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);

        // 4.向好友动态表添加动态id
        if (CollectionUtil.isNotEmpty(friendList)) {
            for (Friend friend : friendList) {
                // 取出好友id
                Long friendId = friend.getFriendId();
                // 设置好友动态
                FriendMovement friendMovement = new FriendMovement();
                friendMovement.setUserId(movement.getUserId()); // 发布人id（好友）
                friendMovement.setPublishId(movementId); // 动态id
                friendMovement.setCreated(movement.getCreated());// 发布时间
                // 保存
                mongoTemplate.save(friendMovement, ConstantUtil.MOVEMENT_FRIEND + friendId); // 指定发布人的好友id
            }
        }

    }

    // 查看我的动态
    @Override
    public PageBeanVo findMyMovementByPage(Long userId, Integer pageNum, Integer pageSize) {
        // 1.构建我的动态查询对象
        Integer index = (pageNum - 1) * pageSize;
        Query query = new Query()
                .with(Sort.by(Sort.Order.desc("created"))) // 排序
                .skip(index).limit(pageSize);// 分页

        //  2.查询我的动态
        List<MyMovement> myMovementList = mongoTemplate.find(query, MyMovement.class, ConstantUtil.MOVEMENT_MINE + userId);
        // 3.遍历并封装动态详情
        List<Movement> movementList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(myMovementList)) {
            for (MyMovement myMovement : myMovementList) {
                // 获取动态id
                ObjectId movementId = myMovement.getPublishId();
                // 查询动态详情
                Movement movement = mongoTemplate.findById(movementId, Movement.class);
                // 审核通过的添加到集合中
                if (movement.getState() == 1) {
                    movementList.add(movement);
                }
            }
        }
        // 4.查询总记录数
        long count = mongoTemplate.count(query, MyMovement.class, ConstantUtil.MOVEMENT_MINE + userId);
        // 5.返回分页对象
        return new PageBeanVo(pageNum, pageSize, count, movementList);
    }

    // 查看好友动态
    @Override
    public PageBeanVo findFriendMovementByPage(Long userId, Integer pageNum, Integer pageSize) {
        // 1.构建查询对象
        Integer index = (pageNum - 1) * pageSize;
        Query query = new Query()
                .with(Sort.by(Sort.Order.desc("created")))// 排序
                .skip(index).limit(pageSize);//分页
        // 2.查询好友动态表
        List<FriendMovement> friendMovementList = mongoTemplate.find(query, FriendMovement.class, ConstantUtil.MOVEMENT_FRIEND + userId);
        // 3.封装动态详情
        List<Movement> movementList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(friendMovementList)) {
            for (FriendMovement friendMovement : friendMovementList) {
                // 取出动态id
                ObjectId movementId = friendMovement.getPublishId();
                // 查询动态详情
                Movement movement = mongoTemplate.findById(movementId, Movement.class);
                // 添加到集合中
                if (movement.getState() == 1) {
                    movementList.add(movement);
                }
            }
        }
        // 4.查询总记录数
        long count = mongoTemplate.count(query, FriendMovement.class, ConstantUtil.MOVEMENT_FRIEND + userId);
        // 5.返回分页对象
        return new PageBeanVo(pageNum, pageSize, count, movementList);
    }

    // 查询推荐动态
    @Override
    public PageBeanVo findRecommendMovementByPage(Long userId, Integer pageNum, Integer pageSize) {
        // 1.构建查询对象
        Integer index = (pageNum - 1) * pageSize;
        Query query = new Query(Criteria.where("userId").is(userId))// 条件
                .with(Sort.by(Sort.Order.desc("score")))// 排序
                .skip(index).limit(pageSize);// 分页
        // 2.查询推荐表
        List<RecommendMovement> recommendMovementList = mongoTemplate.find(query, RecommendMovement.class);
        // 3.封装并查询动态详情
        List<Movement> movementList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(recommendMovementList)) {
            for (RecommendMovement recommendMovement : recommendMovementList) {
                // 取出动态id查询动态详情
                Movement movement = mongoTemplate.findById(recommendMovement.getPublishId(), Movement.class);
                if (movement.getState() == 1) {
                    movementList.add(movement);
                }
            }
        }
        // 4.查询总记录数
        long count = mongoTemplate.count(query, RecommendMovement.class);
        // 5.返回分页对象
        return new PageBeanVo(pageNum, pageSize, count, movementList);
    }

    @Override
    public Movement findMovementById(ObjectId id) {
        return mongoTemplate.findById(id, Movement.class);
    }

    // 查询指定用户id或状态的动态分页
    @Override
    public PageBeanVo findMovementByUserIdAndState(Long userId, Integer state, Integer pageNum, Integer pageSize) {
        // 1.组装查询条件
        Query query = new Query().with(Sort.by(Sort.Order.desc("created")))
                .skip((pageNum - 1) * pageSize).limit(pageSize);

        // 动态条件
        if (userId != null) {
            query.addCriteria(Criteria.where("userId").is(userId));
        }
        if (state != null) {
            query.addCriteria(Criteria.where("state").is(state));
        }

        // 2.查询list
        List<Movement> movementList = mongoTemplate.find(query, Movement.class);

        // 3.查询count
        long count = mongoTemplate.count(query, Movement.class);

        // 4.返回分页对象
        return new PageBeanVo(pageNum, pageSize, count, movementList);
    }

    // 更新审核状态
    @Override
    public void updateMovement(Movement movement) {
        mongoTemplate.save(movement);
    }
}
